package com.xjscrm.server.service.filterrule.impl;

import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.Tools;
import com.xjscrm.server.req.filterrule.CustomerFilterRuleReq;
import com.xjscrm.server.req.filterrule.CustomerTimeExcludeFilterReq;
import org.apache.commons.lang3.StringUtils;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.Objects;

/**
 * 根据时间条件好友排除过滤器
 */
public class CustomerTimeExcludeFilter extends AbstractCustomerExcludeFilter{

    private CustomerTimeExcludeFilter() {
    }

    private final static CustomerTimeExcludeFilter INSTANCE = new CustomerTimeExcludeFilter();



    @Override
    public Boolean filter(CustomerFilterRuleReq req) {
        CustomerTimeExcludeFilterReq filterReq = (CustomerTimeExcludeFilterReq) req;
        if (filterReq.getCreateTime() == null) {
            return false;
        }
        String customerCreateDayStart = filterReq.getExcludeCustomerCreateDayStart();
        String customerCreateDayEnd = filterReq.getExcludeCustomerCreateDayEnd();
        Date date = new Date(filterReq.getCreateTime() * 1000L);
        if (Objects.equals(filterReq.getFlag(), 1) && DateUtil.isSameDay(date, new Date())) {
            return true;
        }
        if (!filterReq.isOpenExclude()) {
            return false;
        }
        if (StringUtils.isBlank(customerCreateDayStart) || StringUtils.isBlank(customerCreateDayEnd)) {
            return false;
        }
        Integer customerCreateTime = filterReq.getCreateTime();
        //判断旧发送时间是否在允许区间内
        Instant instant_groupCreateTime = Instant.ofEpochMilli(customerCreateTime * 1000L);
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant_groupCreateTime, ZoneId.systemDefault());
        return Tools.isWithinDateInterval(localDateTime, LocalDate.parse(customerCreateDayStart), LocalDate.parse(customerCreateDayEnd));
    }


    public static CustomerTimeExcludeFilter getInstance() {
        return INSTANCE;
    }
}
